#include "piceditor.h"
#include <qpainter.h>
#include <qdebug.h>
#include "globesetting.h"
PicEditor::PicEditor(QObject *parent) :
	QThread(parent),pix(0),end(0)
{
}
PicEditor::~PicEditor()
{
	if(pix)
		delete pix;
}

void PicEditor::run()
{
	//end=1;
	qDebug()<<"start";
	mutex.lock();
	qDebug()<<"com="<<com;
	end=0;
	if(com==open)
	{
		openPic();
	}else if(com==scale)
	{
		scalePic();
	}else if(com==rotate)
	{
		rotatePic();
	}
	mutex.unlock();
}

void PicEditor::openPic(const QString &fileName, double scaleFactor)
{
	end=1;
	qDebug()<<"openPic1";
	fn=fileName;
	com=open;
	sf=scaleFactor;
	start();
}
void PicEditor::scalePic(const double &scaleFactor,const QPixmap *p)
{
	qDebug()<<"scalePic";
	if(!p)
		return;
	end=1;
	sf=scaleFactor;
	com=scale;
	if(pix)
		delete pix;
	pix = new QPixmap(p->size());
	*pix=*p;
	start();
}
void PicEditor::rotatePic(int rr)
{
	end=1;
	r=rr;
	com=rotate;
	start();
}
void PicEditor::openPic()
{
	qDebug()<<"openPic";
	if(pix)
		delete pix;
	pix=0;

	QImage image(fn);

	if (image.isNull())
	{
		qDebug()<<"null";

		pix=new QPixmap(200,40);
		QPainter p(pix);
		p.setBrush(Qt::white);
		p.drawRect(0,0,200,40);
		p.drawText(20,10,QString(tr("Cannot load this picture")));
		emit changed(*pix);
		return;
	}
	qDebug()<<"not Null";
	qDebug()<<"filename="<<fn;
	pixsize=image.size();
	qDebug()<<"size="<<pixsize;
	pix=new QPixmap(pixsize);
	/*{
		QPainter p(pix);
		p.setBrush(Qt::white);
		p.drawRect(0,0,image.size().width(),image.size().height());
		p.drawText(20,10,QString(tr("Loading Picture")));
	}
	emit changed(*pix);*/
	//if(end)
	//	return;
	*pix=QPixmap::fromImage(image.scaled(sf*pixsize));
	emit changed(*pix);
	if(pix)
		delete pix;
	pix=0;
}
void PicEditor::scalePic()
{
	if(!pix)
		return;
	*pix=pix->scaled(pixsize*sf);
	if(sizeof(*pix)>globeSetting::maxPicMem)
	{
		delete pix;
		return;
	}
	emit changed(*pix);
	if(end)
		return;
	try
	{
		if(fn.isEmpty())
			throw 1;
		QImage image(fn);
		if(image.isNull())
			throw 1;
		*pix=QPixmap::fromImage(image.scaled(pixsize*sf));
		emit changed(*pix);
	}catch(...)
	{
		{
			QPainter p(pix);
			p.setBrush(Qt::white);
			p.drawRect(0,0,200,40);
			p.drawText(20,10,QString(tr("Cannot load this picture")));
		}
		emit changed(*pix);
		return;
	}
}
void PicEditor::rotatePic()
{

}
const QPixmap *PicEditor::pixmap()
{
	return pix;
}
